import { ref, onMounted, onScopeDispose,nextTick  } from "vue";
import { getUser } from "@/api/user";
import { addCallLog } from "@/api/customer";
// import { getToken, formatToken } from "@/utils/auth";
import { message } from "@/utils/message";
import FingerprintJS from "@fingerprintjs/fingerprintjs";
import { useUserStoreHook } from "@/store/modules/user";
export function useWx() {
  const staffId = ref("");
  const customerData = ref<any>({});
  //-----------------------1.长连接控制-----------------------

  //1.1相关物料
  //1.1.1WebSocket 实例
  let ws: WebSocket | null = null;
  //1.1.2重连超时控制
  let reconnectTimeout = null;
  let checkTimer: NodeJS.Timeout | null = null;
  let heartTimer: NodeJS.Timeout | null = null;

  const each_status = ref(""); // 判断app和pc是否登录 'pc'app未登录 'pc、app' 都已登录
  const callInfo = ref({ status: 0 }); // 通话信息
  const uuid = ref(""); // 通话id
  //1.2建立socket连接
  const connectWebSocket = async () => {
    //ws=new WebSocket("ws://114.117.212.166:2345");
    ws = new WebSocket("wss://crm.wxbqq.com/wsa");
    const result = await FingerprintJS.load();
    const visitorId = await result.get();
    sendData.value.deviceId = visitorId.visitorId;
    ws.onopen = () => {
      ws.send(
        JSON.stringify({ action: "connection_mark", data: sendData.value })
      );
      console.log("WebSocket 连接已建立");
    };
    ws.onmessage = (event) => {
      console.log("onmessage-----", event.data);
      try {
        let data = event.data === "connected" ? event : JSON.parse(event.data);
        // 心跳连接事件
        if (data.action == "connection_beat") {
          if (data.each_status == "pc") {
            each_status.value = data.each_status;
          } else {
            each_status.value = data.each_status;
          }
        }
        // 通话状态事件
        if (data.action == "call_status") {
          callInfo.value = data.data;
          uuid.value = data.data.info.uuid;
          let status = data.data.info.status;
          // 1：来电响铃 2：去电或来电通话中 3：电话挂断 4：来电拒接或未接听 5：去电对方拒接或未接听 6：通话时来电战线
          if (status === 3 || status === 4 || status === 5 || status === 6) {
            addCallLog({
              customer_id: customerData.value.id || "",
              uuid: data.data.info.uuid || "",
              merchant_id: customerData.value.merchant_id || "",
              staff_id: staffId.value || "",
              phone: customerData.value.phone || "",
              record: data.data.record || "",
              callTime: data.data.info.duration || "",
              status: data.data.info.status || "",
              company_name: customerData.value.company_name || "",
              name: customerData.value.name || "",
            }).then(res => {
              if (res.code == 10000) {
                console.log("添加通话记录成功");
              }
            });
          }
        }
        
        // 判断挤占优化
        if(data.action == "deviceIdLose"){
          if(data.data.deviceId === visitorId.visitorId){
            console.log('visitorId----',visitorId.visitorId)
            message(`当前账号已在其他设备登录`, { type: "error" });
            useUserStoreHook().logOut();
            // window.location.href = "/login";
          }
        }
      } catch (e) {
        console.log("error----=====", e);
      }
    };
    ws.onerror = error => {
      console.error("WebSocket 发生错误", error);
      message(`WebSocket 发生错误`, { type: "error" });
    };
    ws.onclose = event => {
      console.log("WebSocket 连接已关闭", event.code);
      message(`WebSocket 连接已关闭 code：${event.code}`, { type: "error" });
    };
  };

  //1.3处理 WebSocket 连接断开后的重连
  const handleReconnect = () => {
    if (reconnectTimeout) {
      // 如果已经在重连，避免重复重连
      return;
    }
    reconnectTimeout = setTimeout(() => {
      console.log("正在尝试重新连接 WebSocket...");
      connectWebSocket();
      reconnectTimeout = null; // 重连后清除重连超时
    }, 5000); // 5 秒后重连
  };
  //1.4发送心跳包
  const sendData = ref({
    platform: "pc",
    staffId: "",
    deviceId:""
  });

  const sendHeartbeat = async () => {
    const result = await FingerprintJS.load();
    const visitorId = await result.get();
    sendData.value.deviceId = visitorId.visitorId;
    if (ws && ws.readyState == WebSocket.OPEN) {
      ws.send(
        JSON.stringify({ action: "connection_beat", data: sendData.value })
      );
      console.log("发送心跳", sendData.value);
    }
  };
  // 发送拨打电话需要的消息
  const callData = ref({
    platform: "pc",
    staffId: "",
    id: "",
    phone: "",
    deviceId:""
  });
  async function changeSend () {
    const result = await FingerprintJS.load();
    const visitorId = await result.get();
    callData.value.deviceId = visitorId.visitorId;
    callData.value.staffId = staffId.value;
    callData.value.id = customerData.value.id;
    callData.value.phone = customerData.value.phone;
    ws.send(JSON.stringify({ action: "call_phone", data: callData.value }));
    console.log("发送消息", callData.value);
  }

  //1.5检查WebSocket连接状态
  const checkConnectionStatus = () => {
    if (ws.readyState === WebSocket.OPEN) {
      console.log("WebSocket 连接正常");
    } else if (ws.readyState === WebSocket.CONNECTING) {
      console.log("WebSocket 正在连接...");
    } else if (ws.readyState === WebSocket.CLOSING) {
      console.log("WebSocket 连接正在关闭...");
    } else if (ws.readyState === WebSocket.CLOSED) {
      console.log("WebSocket 连接已关闭，准备重连");
      handleReconnect();
    }
  };

  onMounted(() => {
    getUser().then(res => {
      if (res.code == 1000) {
        staffId.value = res.data.id;
        sendData.value.staffId = res.data.id;
        connectWebSocket();
        heartTimer = setInterval(sendHeartbeat, 5000); //发送心跳
        checkTimer = setInterval(checkConnectionStatus, 5000); //检查WebSocket状态
      }
    });
  });

  const destory = () => {
    ws.onopen = null;
    ws.onmessage = null;
    ws.onclose = null;
    ws.onerror = null;
    ws?.close();
    ws = null;
    clearInterval(heartTimer);
    clearInterval(checkTimer);
    heartTimer = null;
    checkTimer = null;
  };

  onScopeDispose(() => {
    destory()
  });

  return {
    customerData,
    callInfo,
    uuid,
    staffId,
    sendData,
    callData,
    each_status,
    sendHeartbeat,
    changeSend
  };
}
